package FileIO;

import javax.swing.plaf.synth.SynthLookAndFeel;
import java.io.*;
import java.util.Scanner;

public class CopyFile {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要复制的文件：");
        String srcPath = scanner.next();

        File srcFile = new File(srcPath);
        if (!srcFile.exists()) {
            System.out.println("该文件不存在，退出程序");
            return;
        }
        if (!srcFile.isFile()) {
            System.out.println("该文件不是普通文件，请检查路径");
            return;
        }

        System.out.println("请输入要复制到的目标路径：");
        String destPath = scanner.next();
        File destFile = new File(destPath);

        if (destFile.exists()) {
            if (destFile.isDirectory()) {
                System.out.println("目标路径已存在，且为目录，请检查输入");
                return;
            }
            if (destFile.isFile()) {
                System.out.println("目标路径已存在，是否覆盖？ y/n");
            }
            String ans = scanner.next();
            if (!ans.equalsIgnoreCase("y")) {
                System.out.println("停止复制");
                return;
            }
            try(InputStream is = new FileInputStream(srcFile)) {
                try(OutputStream os = new FileOutputStream(destFile)) {
                    byte[] buf = new byte[1024];
                    int len = 0;
                    while (true) {
                        len = is.read(buf);
                        if (len == -1) break;
                        os.write(buf,0,len);
                    }
                    os.flush();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
